package cao.oschina.function.multiple.news;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import cao.oschina.R;
import cao.oschina.activity.ToolBarActivity;
import cao.oschina.api.URLs;
import cao.oschina.bean.Refer;
import cao.oschina.util.FileUtils;
import cao.oschina.util.TimeUtil;
import cao.oschina.widget.PushDownListView;
import cao.oschina.widget.RefreshView;
import hd.util.ToastUtil;
import hd.util.adapter.BaseViewHolder;
import hd.util.adapter.UniAdapter;
import hd.util.http.HttpClient;
import hd.util.http.HttpRequestListener;
import hd.util.http.HttpResponse;
import hd.util.load.ImageLoader;
import hd.util.widget.listview.BasePushDownListView;
import hd.util.widget.listview.BasePushDownListView.OnScrollStateChangedListener;

/**
 * 新闻评论
 * <p/>
 * Created by Haidy on 15/4/1.
 */
public class Comment extends ToolBarActivity implements OnScrollStateChangedListener {

    public static final int TYPE_NEWS_COMMENT = 0;
    public static final int TYPE_BLOG_COMMENT = 1;

    private PushDownListView listView;
    private CommentAdapter adapter;

    private boolean getAll = false;
    private int pageIndex = 0;
    private String id;
    private int type = TYPE_NEWS_COMMENT;

    /**
     * 初始化界面
     */
    @Override
    protected void initView() {
        configBack();
        setTitle("评论列表");
        setBody(R.layout.comment_view);
        listView = (PushDownListView) findViewById(R.id.comment_list_view);
        listView.setOnScrollStateChangedListener(this);
        adapter = new CommentAdapter(this);
        listView.setAdapter(adapter);
        listView.setOnRefreshListener(new PushDownListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isLoading) {
                    getAll = false;
                    pageIndex = 0;
                    loadData(true);
                }
            }
        });
        listView.setOnLoadNextPageListener(new BasePushDownListView.OnLoadNextPageListener() {
            @Override
            public void onLoad() {
                if (!getAll && !isLoading) {
                    pageIndex++;
                    loadData(false);
                }
            }
        });
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        id = getIntent().getStringExtra("id");
        type = getIntent().getIntExtra("type", TYPE_NEWS_COMMENT);
        loadData(true);
    }

    /**
     * 加载数据
     *
     * @param refresh 刷新
     */
    private void loadData(final boolean refresh) {
        listView.setEnabled(false);
        isLoading = true;
        new HttpClient().httpGet(getUrl(), new HttpRequestListener() {
            @Override
            public void success(HttpResponse response) {
                List<cao.oschina.bean.Comment> data = cao.oschina.bean.Comment.parser(response.text);
                if (refresh) {
                    adapter.setData(data);
                } else {
                    if (adapter.getCount() != 0) {
                        adapter.remove(adapter.getCount() - 1);
                    }
                    if (data.size() < 20) {
                        getAll = true;
                    }
                    adapter.addAllData(data);
                }
                adapter.addData(null);
                listView.overHeadScroll();
                listView.setEnabled(true);
            }

            @Override
            public void failure(HttpResponse response) {
                ToastUtil.toastShort(response.info);
            }

            @Override
            public void end() {
                isLoading = false;
            }
        });
    }

    /**
     * 获取url
     *
     * @return url
     */
    private String getUrl() {
        if (type == TYPE_NEWS_COMMENT) {
            return URLs.COMMENT_LIST + "?pageSize=20&id=" + id + "&catalog=" + cao.oschina.bean.Comment.CATALOG_NEWS + "&pageIndex=" + pageIndex;
        } else if (type == TYPE_BLOG_COMMENT) {
            return URLs.BLOG_COMMENT_LIST + "?pageSize=20&id=" + id + "&pageIndex=" + pageIndex;
        }
        return null;
    }

    @Override
    public void onStateChanged(int state) {
        if (state == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 评论列表适配器
     */
    private class CommentAdapter extends UniAdapter<cao.oschina.bean.Comment, ViewHolder> {

        private ImageLoader imageLoader;

        public CommentAdapter(Context context) {
            super(context);
            imageLoader = new ImageLoader();
            imageLoader.setImageRes(R.mipmap.ic_account_circle_grey600_36dp);
        }

        @Override
        public int getContentView() {
            return R.layout.comment_list_item;
        }

        @Override
        public BaseViewHolder<cao.oschina.bean.Comment, ViewHolder> getHolder() {
            return new BaseViewHolder<cao.oschina.bean.Comment, ViewHolder>() {
                @Override
                public void loadData(ViewHolder holder, cao.oschina.bean.Comment data, int position) {
                    if (position != getCount() - 1) {
                        holder.itemView.setVisibility(View.VISIBLE);
                        holder.nextPagerView.setVisibility(View.GONE);
                        holder.authorView.setText(data.author);
                        holder.pubDataView.setText(TimeUtil.friendTime(data.pubDate));
                        holder.contentView.setText(data.content);
                        holder.appClientView.setVisibility(View.VISIBLE);
                        if (data.appclient == cao.oschina.bean.Comment.CLIENT_ANDROID) {
                            holder.appClientView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_android_grey600_18dp), null, null, null);
                            holder.appClientView.setText(getResources().getString(R.string.android));
                        } else if (data.appclient == cao.oschina.bean.Comment.CLIENT_IPHONE) {
                            holder.appClientView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_iphone_grey600_18dp), null, null, null);
                            holder.appClientView.setText(getResources().getString(R.string.iphone));
                        } else if (data.appclient == cao.oschina.bean.Comment.CLIENT_MOBILE) {
                            holder.appClientView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_android_grey600_18dp), null, null, null);
                            holder.appClientView.setText(getResources().getString(R.string.phone));
                        } else if (data.appclient == cao.oschina.bean.Comment.CLIENT_WINDOWS_PHONE) {
                            holder.appClientView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_android_grey600_18dp), null, null, null);
                            holder.appClientView.setText(getResources().getString(R.string.windows_phone));
                        } else {
                            holder.appClientView.setVisibility(View.GONE);
                        }
                        loadImage(holder.headView, data.portrait);
                        if (data.refers != null && data.refers.size() > 0) {
                            holder.referView.setVisibility(View.VISIBLE);
                            if (holder.referView.getChildCount() == 0) {
                                for (Refer refer : data.refers) {
                                    View view = View.inflate(getBaseContext(), R.layout.refers_view, null);
                                    ((TextView) view.findViewById(R.id.refer_title)).setText(refer.refertitle);
                                    ((TextView) view.findViewById(R.id.refer_body)).setText(refer.referbody);
                                    holder.referView.addView(view);
                                }
                            }
                        } else {
                            holder.referView.setVisibility(View.GONE);
                        }
                    } else {
                        holder.itemView.setVisibility(View.GONE);
                        holder.nextPagerView.setVisibility(View.VISIBLE);
                        if (getAll) {
                            holder.refreshView.setVisibility(View.GONE);
                            holder.refreshTextView.setText(getString(R.string.get_all_data));
                        } else {
                            holder.refreshView.setVisibility(View.VISIBLE);
                            holder.refreshTextView.setText(getString(R.string.loading_next_pager));
                        }
                    }
                }

                /**
                 * 加载头像
                 * @param headView head view
                 * @param portrait 头像地址
                 */
                private void loadImage(final ImageView headView, String portrait) {
                    imageLoader.loadImage(portrait, headView, new ImageLoader.OnImageCacheLoaderListener() {
                        @Override
                        public String onSDCardCache(String url) {
                            return FileUtils.getHeadImagePath(getBaseContext(), url);
                        }
                    });
                }
            };
        }

        @Override
        public ViewHolder initViewHolder(View convertView) {
            return new ViewHolder(convertView);
        }
    }

    private class ViewHolder {

        public final ImageView headView;
        public final TextView authorView;
        public final TextView pubDataView;
        public final TextView contentView;
        public final TextView appClientView;

        public final View itemView;
        public final View nextPagerView;

        public final ViewGroup referView;

        public final RefreshView refreshView;
        public final TextView refreshTextView;

        public ViewHolder(View convertView) {
            itemView = convertView.findViewById(R.id.item_view);
            nextPagerView = convertView.findViewById(R.id.next_pager);

            refreshView = (RefreshView) convertView.findViewById(R.id.next_pager_refresh_view);
            refreshTextView = (TextView) convertView.findViewById(R.id.pager_text_view);
            referView = (ViewGroup) convertView.findViewById(R.id.refer_view);

            headView = (ImageView) convertView.findViewById(R.id.head_view);
            authorView = (TextView) convertView.findViewById(R.id.author);
            pubDataView = (TextView) convertView.findViewById(R.id.pub_date);
            contentView = (TextView) convertView.findViewById(R.id.content);
            appClientView = (TextView) convertView.findViewById(R.id.appclient);
        }
    }

}
